/*
 * PlaceView is used to display the details of single place item
 * 
 * Place view is otherwise straightforward, but reviews are loaded
 * not until rest of the page is first rendered
 * 
 */

qype.views.PlaceView = Class.create(View, {
	
	// Define HTML templates
	templates: {
		details: new Template('<div class="details">'+
					'	<div class="image">#{displayimage}</div>'+
					'	<div class="info">'+
					'		<div class="name">#{title}</div>'+
					'		<div class="address">#{displayaddress}</div>'+
					'		<div class="button map" onclick="EventManager.publish({name:\'mapLinkClicked\'})">Map</div>'+
					'		<div class="distance">#{distance}</div>'+
					'		<div class="rating">#{displayrating}</div>'+
					'		<div class="functions">'+
					'			<div class="button call">#{displaycallto}</div>'+
					'			<div class="button url">#{displayurl}</div>'+
					'		</div>'+
					'		<div class="bar">'+
					'			<span class="text">Information</span>'+
					'		</div>'+
					'		<div class="hours">'+
					'			<div class="icon"></div>'+
					'			<div class="data">'+
					'				<div class="subject">Opening hours</div>'+
					'				<div class="text">#{displayopeninghours}</div>'+
					'			</div>'+
					'		</div>'+
					'		<div class="bar">'+
					'			<span class="text">Reviews</span>'+
					'		</div>'+
					'		<div id="placeReviews" class="reviewContainer"></div>'+
					'	</div>'+
					'</div>'),
        review: new Template('<div class="review">'+
                    '			<div class="icon"></div>'+
                    '			<div class="data">'+
                    '				<div class="subject" id="#{idSummary}" onclick="this.toggle(); util.el(\'#{idFullText}\').toggle()">#{summary}</div>'+
                    '				<div class="fullText" id="#{idFullText}" onclick="this.toggle(); util.el(\'#{idSummary}\').toggle()" style="display: none">#{fullText}</div>'+
                    '				<div class="rating">#{stars}</div>'+
                    '			</div>'+
                    '</div>')
	},

	// Function to generate HTML from template and the given place data
	constructPlaceHtml: function() {
		if(this.data.place) {
            var place = new qype.models.PlaceModel(this.data.place, this.engine.getContentLang());
            var placedata = place.data;

            placedata.displayimage = placedata.image ? "<img src='" + place.getImageUrl("large") + "' class='main' />" : "";
			if(placedata.address) placedata.displayaddress = '<div class="line">'+placedata.address.housenumber+" "+placedata.address.street+'</div>' +
															 '<div class="line">'+placedata.address.postcode+" "+placedata.address.city+'</div>';
			if(placedata.opening_hours) placedata.displayopeninghours = placedata.opening_hours.gsub("\n","<br />");
			if(!placedata.opening_hours) placedata.displayopeninghours = "Not available";

            placedata.distance = this.distance || "- " + qype.str.unit_km;

			placedata.displayrating = '<div class="stars'+placedata.average_rating+'"></div>' + place.getReviewsStr();

			if(placedata.phone) placedata.displaycallto = '<a href="tel:' + placedata.phone + '" onclick="window.widget.openUrl(\'tel:' + placedata.phone + '\')">' + qype.str.place_call + ' (' + placedata.phone + ')</a>';
			if(placedata.url) placedata.displayurl = '<a href="" onclick="window.widget.openURL(\'' + placedata.url + '\'); return false; ">' + qype.str.place_open_www + '</a>';
						
			var template = this.templates.details;
			return template.evaluate(placedata);
        }

        return "";
	},

	// Function to generate review HTML from the review template and the given JSON data
	constructReviewsHtml: function() {
		if(this.data.placeReviews) {
            var arr = [];
            var t = this.templates.review;
            var review = undefined;
            var reviews = this.data.placeReviews;
            for(var i = 0, len = reviews.length; i < len; i++) {
                review = reviews[i].review;
                arr.push(t.evaluate({
                    summary: "<p>" + review.summary + "</p>",
                    fullText: review.content_xhtml,
                    idSummary: review.id + "-summary",
                    idFullText: review.id + "-fullText",
                    stars: '<div class="stars' + review.rating + '"></div>'
                }));
            }

            if(reviews.length == 0) {
                return "<p>" + qype.str.place_no_reviews + "</p>";
            }
            else {
                return arr.join("");
            }
        }

        return "";
	},
	
	initialize: function($super, id) {
		// start with super initialize
		$super(id);
		
		var content = new Snippet("placeContent");
		
		// Create progress->onData mechanism to display loading while content is rendered
		content.onDefault.template.push('<div class="progress"></div>');
        content.onData.template.push({
            fn: this.constructPlaceHtml,
            base: this
        });
        content.onData.doUse = function() {return content.data.place !== undefined;};

		// Same as above
		var reviews = new Snippet();
		reviews.onDefault.template.push('<div class="progress"></div>');
        reviews.onData.template.push({
            fn: this.constructReviewsHtml,
            base: this
        });
        reviews.onData.doUse = function() {return reviews.data.placeReviews !== undefined;};

		// Register the snippets for the view
		this.registerSnippets({
            content: content,
            reviews: reviews
        });
		
		// Register subscribes (button click events)
		this.registerSubscribes([
            {
                eventName: "mapLinkClicked",
                callback: this.onMapLinkClick,
                context: this
            }
        ]);
	},
	
	// Launch map view when map button is clicked
	onMapLinkClick: function() {
		this.engine.activateView("mapView",{placedata:this.data.place});
	},
	
	build: function($super, params) {
        $super(params);
        if(!this.data.place) {
            this.getPlaceData();
        }
	},
	
	render: function($super, params) {
		if (params.placeid && (params.placeid != this.placeId)) {
			this.placeId = params.placeid;
            this.distance = params.distance;
			this.data.place = undefined;
            this.data.placeReviews = undefined;
			this.snippets.content.data.place = undefined;
			this.snippets.content.data.placeReviews = undefined;

            $super(params);
		}
        else {
            $super(params);

            // This "child snippet" needs to be redrawn manually here
            this.snippets.reviews.setDom("placeReviews");
            this.snippets.reviews.rewrite();
        }
	},
	
	getPlaceData: function() {
        qype.API.get("places", {
            "onSuccess": this.onGetPlaceData.bind(this),
            "onFailure": this.onFailure.bind(this)
        }, this.placeId);
    },

    onGetPlaceData: function(response) {
        util.log("{PlaceView.onGetPlaceData} start");
        this.data.place = response.responseJSON.place;
        this.snippets.content.data.place = this.data.place;
		this.snippets.content.rewrite();

        // Init a "child" snippet and attach it to the DOM. It can not be done
        // earlier since the DOM is surely available only now!
        this.snippets.reviews.setDom("placeReviews");
        this.snippets.reviews.rewrite();

        this.getPlaceReviews();
    },

	onFailure: function(response) {
        util.log("{PlaceView.onFailure}: start, response = ");
        util.log(response);
    },

	// Load reviews from Qype API
	getPlaceReviews: function() {
        util.log("{PlaceView.getPlaceReview}: start");
        qype.API.get("places", {
            "onSuccess": this.onGetPlaceReviews.bind(this),
            "onFailure": this.onFailure.bind(this)
        }, this.placeId + '/reviews/' + this.engine.getContentLang());
    },

	// Handle successful response (reviews JSON) from Qype API 
    onGetPlaceReviews: function(response) {
        util.log("{PlaceView.onGetPlaceReviews} start");
        this.data.placeReviews = response.responseJSON.results;
        this.snippets.reviews.data.placeReviews = this.data.placeReviews;
		this.snippets.reviews.rewrite();
    }
});